import {moduleService} from '@/api/index';
import utils from '@/utils/utils';
import {mapGetters} from 'vuex';

export default {
  data() {
    return {
      showModuleForm: false,
      currentModule: {},
      exportModuleShow: false,
      exportList: []
    };
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'addTrigger'
    ]),
    parentId() {
      let parentId = this.$route.params.appId;
      if (!parentId) {
        parentId = this.$route.params.envId;
      }
      return parentId;
    },
    currentModuleId() {
      return this.$route.params.moduleId;
    },
    isOpen() {
      return this.sidebar.opened;
    },
    isEnv() {
      return !!this.$route.params.envId;
    },
    currentMenu() {
      return this.$store.getters.moduleList;
    }
  },
  watch: {
    addTrigger(flag) {
      if (flag) {
        this.addModule();
      }
    }
  },
  mounted() {
    this.getCurrentMenu();
    this.getBreadcrumb();
  },
  methods: {

    edit(currentItem) {
      this.currentModule = currentItem;
      this.showModuleForm = true;
    },
    itemChange(item) {
      if (!this.currentModule.moduleId) {
        this.$store.commit('ADD_TRIGGER', false);
        let mould = this.isEnv ? 'env' : 'app';
        this.$router.push({path: `/${mould}/${this.parentId}/module/${item.moduleId}`});
      }
    },
    deleteRow(currentItem, type = 'app', parentId) {
      this.$confirm('是否确认删除', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('deleteModule', currentItem.moduleId).then(res => {
          this.currentMenu.forEach((item, index) => {
            if (currentItem.moduleId === item.moduleId) {
              if (this.currentModuleId === item.moduleId) {
                this.$router.push({
                  path: `/${type}/${parentId}`
                });
              }
            }
          });
        });
      });
    },
    addModule() {
      let moduleType = this.isEnv ? 1 : 0;
      this.currentModule = {parentId: this.parentId, moduleType: moduleType};
      this.showModuleForm = true;
    },
    getCurrentMenu() {
      let fun = this.isEnv ? 'getEnvModuleList' : 'getAppModuleList';
      this.$store.dispatch(fun, this.parentId).then(res => {
        this.checkEnvModuleFirst();
      });
    },
    checkEnvModuleFirst() {
      let currentModuleId = this.$route.params.moduleId;
      if (this.isEnv && (!currentModuleId || currentModuleId === '0')) {
        let moduleId = 0;
        if (this.currentMenu && this.currentMenu.length > 0) {
          moduleId = this.currentMenu[0].moduleId;
        }
        this.$router.push({path: `/env/${this.parentId}/module/${moduleId}`});
      }
    }
  }
};
